package logic

import (
	"class_rpc/internal/model/elasticsearch"
	"context"
	"github.com/olivere/elastic/v7"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"class_rpc/class"
	"class_rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassListByEsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewClassListByEsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassListByEsLogic {
	return &ClassListByEsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ClassListByEsLogic) ClassListByEs(in *class.ClassListByEsRequest) (*class.ClassListByEsResponse, error) {
	// todo: add your logic here and delete this line
	termQuery := elastic.NewTermQuery("Title", in.Title)
	num, list, err := elasticsearch.EsSearch("classes", termQuery, int(in.Offset), int(in.Limit))
	if err != nil {
		return nil, status.Error(codes.Internal, "es查询失败")
	}
	var classList []*class.ClassInfo
	for _, m := range list {
		classList = append(classList, &class.ClassInfo{
			Title:   m.Title,
			Img:     m.Img,
			IsPay:   int64(m.IsPay),
			UserId:  int64(m.UserId),
			TypeId:  int64(m.TypeId),
			Comment: int64(m.Comment),
			Id:      int64(m.ID),
		})
	}

	return &class.ClassListByEsResponse{Nums: num, ClassInfo: classList}, nil
}
